package com.note.backend.controller.file;

import com.note.backend.pojo.Repository;
import com.note.backend.service.file.RepositoryService;
import com.note.backend.service.impl.utils.UserDetailsImpl;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RequiredArgsConstructor
@RestController
@RequestMapping("/api/repositories")
public class RepositoryController {

    private final RepositoryService repositoryService;
    
    // 获取当前登录用户ID的辅助方法
    private Integer getCurrentUserId() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication != null && authentication.isAuthenticated()) {
            UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
            return userDetails.getUser().getId();
        }
        // 如果未获取到用户信息，可以抛出异常或返回默认值
        throw new RuntimeException("用户未登录");
    }

    @PostMapping
    public Repository createRepository(@RequestBody Map<String, Object> params) {
        String name = (String) params.get("name");
        String description = (String) params.get("description");
        Integer userId = getCurrentUserId();

        return repositoryService.createRepository(name, description, userId);
    }

    @GetMapping
    public List<Repository> getRepositories() {
        Integer userId = getCurrentUserId();
        return repositoryService.getRepositoriesByUserId(userId);
    }

    @GetMapping("/{id}")
    public Repository getRepository(@PathVariable Integer id) {
        return repositoryService.getRepositoryById(id);
    }

    @DeleteMapping("/{id}")
    public void deleteRepository(@PathVariable Integer id) {
        Integer userId = getCurrentUserId();
        repositoryService.deleteRepository(id, userId);
    }
}